package cn.iocoder.yudao.module.erp.service.purchase;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.erp.controller.admin.purchase.vo.out.ErpPurchaseOutPageReqVO;
import cn.iocoder.yudao.module.erp.controller.admin.purchase.vo.out.ErpPurchaseOutSaveReqVO;
import cn.iocoder.yudao.module.erp.controller.app.purchase.vo.out.AppErpPurchaseOutPageReqVO;
import cn.iocoder.yudao.module.erp.controller.app.purchase.vo.out.AppErpPurchaseOutSaveReqVO;
import cn.iocoder.yudao.module.erp.dal.dataobject.product.ErpProductDO;
import cn.iocoder.yudao.module.erp.dal.dataobject.purchase.ErpPurchaseApplyOrderDO;
import cn.iocoder.yudao.module.erp.dal.dataobject.purchase.ErpPurchaseOutDO;
import cn.iocoder.yudao.module.erp.dal.dataobject.purchase.ErpPurchaseOutItemsDO;
import cn.iocoder.yudao.module.erp.dal.mysql.purchase.ErpPurchaseOutItemsMapper;
import cn.iocoder.yudao.module.erp.dal.mysql.purchase.ErpPurchaseOutMapper;
import cn.iocoder.yudao.module.erp.dal.redis.no.ErpNoRedisDAO;
import cn.iocoder.yudao.module.erp.enums.ErpAuditStatus;
import cn.iocoder.yudao.module.erp.enums.ErpPurchaseOutStatus;
import cn.iocoder.yudao.module.erp.enums.stock.ErpStockRecordBizTypeEnum;
import cn.iocoder.yudao.module.erp.service.product.ErpProductService;
import cn.iocoder.yudao.module.erp.service.stock.ErpStockRecordService;
import cn.iocoder.yudao.module.erp.service.stock.bo.ErpStockRecordCreateReqBO;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.*;
import static cn.iocoder.yudao.module.erp.enums.ErrorCodeConstants.*;

/**
 * ERP 基础出库 Service 实现类
 *
 * @author 芋道源码
 */
@Service
@Validated
public class AppErpPurchaseOutServiceImpl implements AppErpPurchaseOutService {

    @Resource
    private ErpPurchaseOutMapper purchaseOutMapper;
    @Resource
    private ErpPurchaseOutItemsMapper purchaseOutItemsMapper;
    @Resource
    private ErpPurchaseApplyOrderService purchaseOrderService;
    @Resource
    private ErpProductService productService;
    @Resource
    private ErpNoRedisDAO noRedisDAO;
    @Resource
    private ErpStockRecordService stockRecordService;


//    @Override
//    @Transactional(rollbackFor = Exception.class)
//    public Long createPurchaseOut(ErpPurchaseOutSaveReqVO createReqVO) {
//
//        String no = noRedisDAO.generate(ErpNoRedisDAO.PURCHASE_OUT_NO_PREFIX);
//        if (purchaseOutMapper.selectByNo(no) != null) {
//            throw exception(PURCHASE_OUT_NO_EXISTS);
//        }
//
//        ErpPurchaseApplyOrderDO purchaseOrder = purchaseOrderService.validatePurchaseOrder(createReqVO.getOrderId());
//        List<ErpPurchaseOutItemsDO> purchaseOutItems = validatePurchaseOutItems(createReqVO.getItems());
//
//
//        // 插入
//        ErpPurchaseOutDO purchaseOut = BeanUtils.toBean(createReqVO, ErpPurchaseOutDO.class, out -> out
//                        .setNo(no).setStatus(ErpPurchaseOutStatus.WAIT.getStatus()))
//                .setOrderNo(purchaseOrder.getNo()).setSupplierId(purchaseOrder.getSupplierId());
//        calculateTotalPrice(purchaseOut, purchaseOutItems);
//        purchaseOutMapper.insert(purchaseOut);
//
//        // 2.2 插入入库项
//        purchaseOutItems.forEach(o -> o.setOutId(purchaseOut.getId()));
//        purchaseOutItemsMapper.insertBatch(purchaseOutItems);
//
//        updatePurchaseOrderOutCount(createReqVO.getOrderId());
//
//        // 返回
//        return purchaseOut.getId();
//    }

    private void updatePurchaseOrderOutCount(Long orderId) {
        // 1.1 查询采购订单对应的采购入库单列表
        List<ErpPurchaseOutDO> purchaseOuts = purchaseOutMapper.selectListByOrderId(orderId);
        // 1.2 查询对应的采购订单项的入库数量
        Map<Long, BigDecimal> returnCountMap = purchaseOutItemsMapper.selectOrderItemCountSumMapByInIds(
                convertList(purchaseOuts, ErpPurchaseOutDO::getId));
        // 2. 更新采购订单的入库数量
        purchaseOrderService.updatePurchaseOrderInCount(orderId, returnCountMap);
    }

    private void calculateTotalPrice(ErpPurchaseOutDO purchaseOut, List<ErpPurchaseOutItemsDO> purchaseInItems) {
        purchaseOut.setTotalCount(getSumValue(purchaseInItems, ErpPurchaseOutItemsDO::getCount, BigDecimal::add));
        // 计算优惠价格
//        purchaseOut.setDiscountPrice(MoneyUtils.priceMultiplyPercent(purchaseOut.getTotalPrice(), purchaseOut.getDiscountPercent()));
//        purchaseOut.setTotalPrice(purchaseOut.getTotalPrice().subtract(purchaseOut.getDiscountPrice()).add(purchaseOut.getOtherPrice()));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updatePurchaseOut(AppErpPurchaseOutSaveReqVO updateReqVO) {
        // 校验存在
        ErpPurchaseOutDO purchaseOut = validatePurchaseOutExists(updateReqVO.getId());

        // 1.2 校验采购申请已审核
        ErpPurchaseApplyOrderDO purchaseOrder = purchaseOrderService.validatePurchaseOrder(updateReqVO.getOrderId());
        // 1.4 校验订单项的有效性
        List<ErpPurchaseOutItemsDO> purchaseOutItems = validatePurchaseOutItems(updateReqVO.getItems());

        // 2.1 更新出库
        ErpPurchaseOutDO updateObj = BeanUtils.toBean(updateReqVO, ErpPurchaseOutDO.class)
                .setOrderNo(purchaseOrder.getNo()).setSupplierId(purchaseOrder.getSupplierId());
        purchaseOutMapper.updateById(updateObj);
        // 2.2 更新入库项
        updatePurchaseOutItemList(updateReqVO.getId(), purchaseOutItems);

        //todo，是否需要更新采购申请的出库数量
        updatePurchaseOrderOutCount(updateObj.getOrderId());

        if (ObjectUtil.notEqual(purchaseOut.getOrderId(), updateObj.getOrderId())) {
            updatePurchaseOrderOutCount(purchaseOut.getOrderId());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updatePurchaseOutStatus(Long id, Integer status) {
        boolean approve = ErpPurchaseOutStatus.OUT.getStatus().equals(status);
        // 1.1 校验存在
        ErpPurchaseOutDO purchaseOut = validatePurchaseOutExists(id);
        // 1.2 校验状态
        if (purchaseOut.getStatus().equals(status)) {
            throw exception(approve ? PURCHASE_IN_APPROVE_FAIL : PURCHASE_IN_PROCESS_FAIL);
        }

        // 2. 更新状态
        int updateCount = purchaseOutMapper.updateByIdAndStatus(id, purchaseOut.getStatus(),
                new ErpPurchaseOutDO().setStatus(status));
        if (updateCount == 0) {
            throw exception(approve ? PURCHASE_IN_APPROVE_FAIL : PURCHASE_IN_PROCESS_FAIL);
        }

        // 3. 变更库存
        List<ErpPurchaseOutItemsDO> purchaseOutItems = purchaseOutItemsMapper.selectListByOutId(id);
        Integer bizType = approve ? ErpStockRecordBizTypeEnum.PURCHASE_IN.getType()
                : ErpStockRecordBizTypeEnum.PURCHASE_IN_CANCEL.getType();
        purchaseOutItems.forEach(purchaseInItem -> {
            BigDecimal count = approve ? purchaseInItem.getCount() : purchaseInItem.getCount().negate();
            stockRecordService.createStockRecord(new ErpStockRecordCreateReqBO(
                    purchaseInItem.getProductId(), purchaseInItem.getWarehouseId(), count,
                    bizType, purchaseInItem.getOutId(), purchaseInItem.getId(), purchaseOut.getNo()));
        });
    }




    private void updatePurchaseOutItemList(Long id, List<ErpPurchaseOutItemsDO> newList) {
        // 第一步，对比新老数据，获得添加、修改、删除的列表
        List<ErpPurchaseOutItemsDO> oldList = purchaseOutItemsMapper.selectListByOutId(id);
        List<List<ErpPurchaseOutItemsDO>> diffList = diffList(oldList, newList, // id 不同，就认为是不同的记录
                (oldVal, newVal) -> oldVal.getId().equals(newVal.getId()));

        // 第二步，批量添加、修改、删除
        if (CollUtil.isNotEmpty(diffList.get(0))) {
            diffList.get(0).forEach(o -> o.setOutId(id));
            purchaseOutItemsMapper.insertBatch(diffList.get(0));
        }
        if (CollUtil.isNotEmpty(diffList.get(1))) {
            purchaseOutItemsMapper.updateBatch(diffList.get(1));
        }
        if (CollUtil.isNotEmpty(diffList.get(2))) {
            purchaseOutItemsMapper.deleteBatchIds(convertList(diffList.get(2), ErpPurchaseOutItemsDO::getId));
        }
    }

    private List<ErpPurchaseOutItemsDO> validatePurchaseOutItems(List<AppErpPurchaseOutSaveReqVO.PurchaseOutSaveItem> list) {
        // 1. 校验产品存在
        List<ErpProductDO> productList = productService.validProductList(
                convertSet(list, AppErpPurchaseOutSaveReqVO.PurchaseOutSaveItem::getProductId));
        Map<Long, ErpProductDO> productMap = convertMap(productList, ErpProductDO::getId);
        // 2. 转化为 ErpPurchaseOutItemsDO 列表
        return convertList(list, o -> BeanUtils.toBean(o, ErpPurchaseOutItemsDO.class, item -> {
            item.setProductUnitId(productMap.get(item.getProductId()).getUnitId());
        }));
    }



    @Override
    public void deletePurchaseOut(Long id) {
        // 校验存在
        validatePurchaseOutExists(id);
        // 删除
        purchaseOutMapper.deleteById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deletePurchaseOutListByIds(List<Long> ids) {
        // 校验存在
        validatePurchaseOutExists(ids);
        // 删除
        purchaseOutMapper.deleteByIds(ids);
        }

    private void validatePurchaseOutExists(List<Long> ids) {
        List<ErpPurchaseOutDO> list = purchaseOutMapper.selectByIds(ids);
        if (CollUtil.isEmpty(list) || list.size() != ids.size()) {
            throw exception(PURCHASE_OUT_NOT_EXISTS);
        }
    }

    private ErpPurchaseOutDO validatePurchaseOutExists(Long id) {
        ErpPurchaseOutDO purchaseOut = purchaseOutMapper.selectById(id);
        if (purchaseOut == null) {
            throw exception(PURCHASE_OUT_NOT_EXISTS);
        }
        return purchaseOut;
    }

    @Override
    public ErpPurchaseOutDO getPurchaseOut(Long id) {
        return purchaseOutMapper.selectById(id);
    }

    @Override
    public PageResult<ErpPurchaseOutDO> getPurchaseOutPage(AppErpPurchaseOutPageReqVO pageReqVO) {
        return purchaseOutMapper.selectAppJoinPage(pageReqVO);
    }

    @Override
    public List<ErpPurchaseOutItemsDO> getPurchaseOutItemListByOutId(Long outId) {
        return purchaseOutItemsMapper.selectListByOutId(outId);
    }

    @Override
    public List<ErpPurchaseOutItemsDO> getPurchaseOutItemListByOutIds(Collection<Long> outIds) {
        if (CollUtil.isEmpty(outIds)) {
            return Collections.emptyList();
        }
        return purchaseOutItemsMapper.selectListByInIds(outIds);
    }

}
